package com.example.game.sdk.framework.plugin.channel

import android.content.Context
import com.example.game.sdk.framework.GameApiCallback
import com.example.game.sdk.framework.plugin.DispatcherTemplate
import com.example.game.sdk.framework.plugin.PluginTemplate
import org.json.JSONObject

internal class ChannelDispatcher() : DispatcherTemplate() {
    //一般只会有一个渠道对象
    private var channelTemplate: ChannelTemplate? = null

    override val lifecycleDispatchList: MutableList<PluginTemplate> = mutableListOf()

    override val dispatcherName: String = "channel"
    /**
        核心思想利用反射动态创建对象。需要得知类的全限定名。有四种方式：
        1, 硬编码，代码中维护 所有插件的类名，运行时遍历集合，有则创建
        2, 配置文件，json/xml 配置文件中维护
        3, 注解+APT，编译时解析注解 生成class实现逻辑 或 字节码注入
        4, classLoader+DexFile，获取指定包名下所有类，通过反射创建对象
     */
    private val clazzList: List<String> = listOf(
        "com.example.game.sdk.channel.mock.MockChannel",
        "com.example.game.sdk.channel.real.RealChannel",
    )

    override fun attachBaseContext(context: Context) {
        clazzList.forEach {
            try {
                val clazz = Class.forName(it)
                val instance = clazz.getDeclaredConstructor().newInstance()
                if (instance is ChannelTemplate) {
                    channelTemplate = instance
                    return@forEach
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        channelTemplate?.let {
            lifecycleDispatchList.add(it)
            it.attachBaseContext(context)
        }
    }


    fun login(callback: GameApiCallback){
        channelTemplate?.login(callback)
    }

    fun logout(callback: GameApiCallback){
        channelTemplate?.logout(callback)
    }

    fun pay(params: JSONObject,callback: GameApiCallback){
        channelTemplate?.pay(params,callback)
    }
}